import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

export const serverUrl = "http://localhost:1337";

const service = axios.create({
  baseURL: serverUrl,
  timeout: 5000,
});

// Add a request interceptor 全局请求拦截
service.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    NProgress.start(); // 启动进度条
    // 此处还可以设置token
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor 全局相应拦截
service.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    NProgress.done();

    // 如果是固定的数据返回模式，此处可以做继续完整的封装
    return response.data;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    NProgress.done();

    // 此处需要对返回的状态码或者异常信息作统一处理
    return Promise.reject(error);
  }
);

export const get = (url, params) => {
  return service.get(url, {
    params,
  });
};

export const post = (url, data) => service.post(url, data);

export const put = (url, data) => service.put(url, data);

export const del = (url, data) => service.delete(url);
